//require('../lib/Framework7/dist/js/framework7.js');

define('utils',["config","moment"],function(config,moment){
	'use strict';

	var Utils = {

        //提示弹框
        appAlert:function(msg,callback1,text1,callback2,text2,title){
            var text1 = text1 ? text1: "确定";
            var callback1 = callback1 ? callback1:function(){
                $('.framework7-root').css({'overflow-y':'scroll'});
            }
            var buttons;
            if(text2){
                buttons = [
                    {
                        text:text1,
                        bold:true,
                        onClick:callback1
                    },
                    {
                        text:text2,
                        bold:true,
                        onClick:callback2
                    }
                ]
            }else{
                buttons = [
                    {
                        text:text1,
                        bold:true,
                        onClick:callback1
                    }
                ];
            }
            var myApp = new Framework7();
            myApp.modal({
                title: title,
                text: '<span style="font-size:16px;">'+msg+'</span>',
                buttons: buttons
            });
        },

        //添加url#
        pushHistory:function(){
            var state = {  
                title: "title",  
                url: "#"  
            };  
            window.history.pushState(state, "title", "#"); 
        },

        //监听浏览器返回事件
        cancleHistory:function(){
            var state = {  
                title: "title",  
                url: ""  
            };  
            window.history.pushState(state, "title", ""); 
        },

        //时间戳 => 日期
        localDate:function(date){
            var arr = moment(date*1000).format('YYYY-MM-DD').split('-');
            return arr[0]+'年'+arr[1]+'月'+arr[2]+'日';
        },

        //日期 => 时间戳
        getTime:function(value){
            return moment(value).format('X');
        },

        getWebUrl:function(url){
            if(__ENV__.toLowerCase()==="mock"){
               return config.api.root + url;
            }else{
               return config.api.root + url;
            }
        },

        getPicUrl:function(url){
            if(__ENV__.toLowerCase()==="mock"){
               return  url;
            }else{
               return  url;
            }
        },

        copyText:function(text){
            window.clipboardData.setData("text",text);   
            return;
        },

        abbreviation:function(value){
            if(value>=10000){
                return (value/10000).toFixed(2) +'万';
            }else{
                if(value === 0){
                    return '0';
                }else{
                    return value; 
                }
            }
            /*var value = value >= 10000 ? (value*1/10000).toFixed(2) + '万' : (value*1).toFixed(0);
            return value;*/
        },

		// 获取url参数
        getQueryVariable: function(variable) {
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var i=0;i<vars.length;i++) {
                var pair = vars[i].split("=");
                if(pair[0] == variable){return pair[1];}
            }
            return '';
        },

        /**
         * @param url 请求地址
         * @param data 请求参数
         * @param suc 成功后的回调函数
         */
        ajax: function(url,data,type,suc,beforeRequest,finishRequest,error,unsuc) {
            var _this=this,
            beforeRequest = beforeRequest ? beforeRequest : null,
            finishRequest = finishRequest ? finishRequest : null,
            defaultError = function(res){
                _this.appAlert('系统出现了错误,系统管理员正在修复')
            };
            var thatError;
            if(error){
                thatError = error;
            }else{
                thatError = defaultError;
            }
            $.ajax({
                url: url,
                type: type,
                data: data,
                dataType: 'json',
                traditional: true,
                headers: {
                   'authorization': 'Bearer '+_this.userToken()
                },
                contentType:"application/x-www-form-urlencoded; charset=utf-8",
                beforeSend:beforeRequest,
                complete:finishRequest,
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function(res) {
                    //console.log(res)
                    if(res.code === "10000"){
                        suc(res);
                    }else{
                        if(unsuc){
                            unsuc(res);
                        }else{
                            _this.appAlert(res.msg);
                        }
                    }
                },
                error: function(res){
                    thatError(res);
                }
            });
        },

        initAjax: function(url,data,type,suc,beforeRequest,finishRequest,error,unsuc){
            var url = this.getWebUrl(url);
            var _this = this,
            beforeRequest = beforeRequest ? beforeRequest : null,
            finishRequest = finishRequest ? finishRequest : null;
            $.ajax({
                url: url,
                type: type,
                data: data, 
                dataType: 'json',
                contentType:"application/x-www-form-urlencoded; charset=utf-8",
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                beforeSend:beforeRequest,
                complete:finishRequest,
                success: function(res) {
                    // if(res.code === "10000"){
                    //     suc(res);
                    // }else{
                    //     _this.appAlert(res.msg);
                    // }
                    if(res.code === "10000"){
                        suc(res);
                    }else{
                        if(unsuc){
                            unsuc(res);
                        }else{
                            _this.appAlert(res.msg);
                        }
                    }
                },
                error: function(res) {
                    if(error){
                        error(res);
                    }else{
                        _this.appAlert('系统出现了错误,系统管理员正在修复');
                    }
                    
                }
            });
        },

        setData: function(k, v) {
            if (typeof v === 'object') {
                v = JSON.stringify(v);
            }
            localStorage.setItem(k,v);
        },

        /**
         * 封装本地存储
         * 取
         * @param k string
         */
        getData: function(k) {
            var v = localStorage.getItem(k);
            try {
                v = JSON.parse(v);
            } catch(e) {

            }
            return v;
        },

        userToken: function (token) {
            var token = token;

            if (token) {
                localStorage.setItem('token',token);
            } else {
                token = localStorage.getItem("token");
            }
            if (!window.location.href.match("login.html") && !token) {
                window.location.href = "login.html";
            }

            return token;
        },

        logout: function () {
            //清除所有本地存储
            var local=window.localStorage;  
            console.log(local)

            localStorage.setItem('token','');
            if (!window.location.href.match("login.html")) {
                window.location.href = "login.html";
            }
        },

        //清除所有本地缓存
        clearData: function() {
            var local=window.localStorage;
            var _this = this;
            $.each(local,function(k,p){
                //console.log(k+'======'+p)
                if(k !=='phone'){
                   _this.setData(k,'');  
                }
                //console.log(k+'======'+p)
            })
        },

        /*时间戳转化为出生日期*/
        getLocalTime: function (time) {
          var tt = new Date(parseInt(time) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ").split(' ')[0].split('/');
          var y,m,d;

          /*兼容微信浏览器*/
          if(this.isWeiXin()){
            y = tt[2].slice(0,4);m = tt[0];d = tt[1];
          }else{
            y = tt[0];m = tt[1];d = tt[2];
          }
          return (y + "年" + m +"月" + d + "日");
        },

        /*日期转化为时间戳*/
        getTimesTamp:function(y,m,d){
            var datum = new Date(Date.UTC(y,m*1-1,d));
            return datum.getTime()/1000;
        }, 

        /*判断是否为微信浏览器*/
        isWeiXin:function(){
            var ua = window.navigator.userAgent.toLowerCase();
            if(ua.match(/MicroMessenger/i) == 'micromessenger'){
                return true;
            }else{
                return false;
            }
        },

        /*隐藏手机号码中间部分*/
        showPhone:function(phone){
            var start = phone.toString().slice(0,3);
            var end = phone.toString().slice(phone.toString().length-3,phone.toString().length);
            return (start + '*****' + end)
        },

        //隐藏银行卡账号
        hidden:function(value){
            return value.slice(0,4) + "*********" + value.slice(-4);
        },

        /*复制到粘贴板
        * @param text 要复制的内容
        */
        copyToClipboard:function(aux){

                // 复制内容
                aux.select();

                // 将内容复制到剪贴板
                document.execCommand("copy");

                $('.popmsg').show();
                setTimeout(function(){
                   $('.popmsg').hide();
                },1000)
                
        },

        /*去掉空格*/
        Trim:function(str,is_global){
            var result;
            result = str.toString().replace(/(^\s+)|(\s+$)/g,"");
            if(is_global.toLowerCase()=="g")
            {
                result = result.replace(/\s/g,"");
             }
            return result;
        },
        //选中不选中
        checked:function(event){
            event.addClass('checked');
        },

        unchecked:function(event){
            event.removeClass('checked');
        }
	};

    return Utils;
})